Cuestionario Ampliado del Censo de Población y Vivienda 2010

El cuestionario ampliado se guarda en un un archivo .RData.

data <- read_sav("~/Población 2010/Cuestionario Ampliado_2010_Persona.sav")

save(data, 
      file = paste0(here::here(),"/Bases/Censo_Personas_2010.RData"))

Se seleccionan las variables que se desean conservar para la realización de este documento y se guarda en un archivo .RData para practicidad del manejo de datos.

Posibles variables que se pueden contemplar en la migración reciente

  • EDAD
  • SEXO
  • AFRODES
  • HLENGUA 
  • QDIALECT_C
  • PERETN 
  • NIVACAD
  • ALFABET
  • ESTCON 
  • CONACT 
  • HIJOS_NAC_VIVOS
load(paste0(here::here(),"/Bases/Censo_Personas_2010.RData"))

mydata <- data %>%
           select(ENT, NOM_ENT, MUN, NOM_MUN, ENT_MUN, 
                  LNACEDO_C, LNACPAIS_C,
                  RES05EDO_C, RES05PAI_C, MUN05OTR_C,
                  LTRABPAI_C, LTRABMUN_C, ENT_MUN_TRABAJO,
                  EDAD, SEXO, HLENGUA, QDIALECT_C, LI_INALI, PERETN, NIVACAD, ALFABET, 
                  ESTCON, CONACT,  OCUACTIV_C, HORTRA, INGTRMEN, SITTRA, FACTOR, ESTRATO, UPM) %>%
            rename("CVE_ENT" = "ENT",
                   "CVE_MUN" = "ENT_MUN",
                   "MUN_TRAB" = "LTRABMUN_C",
                   "CVE_MUN_TRABAJO" = "ENT_MUN_TRABAJO") %>%
             mutate(CVE_ENT = str_pad(.$CVE_ENT, width = 3, side = c("left"), pad = "0"),
                    CVE_MUN = str_pad(.$CVE_MUN, width = 6, side = c("left"), pad = "0")) %>%
              mutate(CVE_MUN_RES = paste0(.$RES05EDO_C, MUN05OTR_C))

Zonas Metropolitanas 2010

Se anexa la base de datos de las Zonas Metropolitanas 2010 a la base orginal

ZM_2010 <- read.xlsx(paste0(here::here(), "/Bases/Municipio/ZM_2010.xlsx"), sheet = "ZM_2010") %>%
            select(CVE_ENT, CVE_MUN, CVE_ZM, NOM_ZM) %>%
             mutate(CVE_ENT = stringr::str_pad(.$CVE_ENT, width = 3, side = c("left"), pad = "0"),
                    CVE_MUN = stringr::str_pad(.$CVE_MUN, width = 6, side = c("left"), pad = "0"))

Se asignan las claves de las zonas metropolitanas de acuerdo a las diferentes variables de interes:

  • Residencia hace 5 años

  • Laboral

mydata <- mydata %>%
           # Zonas Metropolitanas por residenicia
           left_join(., ZM_2010 %>% select(-CVE_ENT), by = c("CVE_MUN")) %>%
            # Zonas Metropolitanas en el lugar de residencia hace 5 años
            left_join(., ZM_2010 %>% select(-CVE_ENT) %>% 
                           rename("CVE_ZM_RES" = "CVE_ZM",
                                  "ZM_RES" = "NOM_ZM"), by = c("CVE_MUN_RES" = "CVE_MUN")) %>%
             # Zonas Metropolitanas en el lugar de trabajo
             left_join(., ZM_2010 %>% select(-CVE_ENT) %>% 
                           rename("CVE_ZM_TRABAJO" = "CVE_ZM",
                                  "ZM_TRABAJO" = "NOM_ZM"), by = c("CVE_MUN_TRABAJO" = "CVE_MUN")) 

save(mydata, file = paste0(here::here(), "/Bases/06_Migracion por Zonas Metropolitanas_2010.RData"))          

✔️A partir de aquí se pueden correr los códidos 👇.
Se carga el archivo Migracion por Zonas Metropolitanas_2010.RData.

load(file = paste0(here::here(), "/Bases/06_Migracion por Zonas Metropolitanas_2010.RData"))  

# Para fines prácticos se genera un ponderador de uno 
mydata <- mydata %>%
           select(CVE_ENT, NOM_ENT, CVE_MUN, NOM_MUN, RES05EDO_C, CVE_MUN_RES, 
                  CVE_ZM, NOM_ZM, CVE_ZM_RES, ZM_RES,
                  EDAD, FACTOR, ESTRATO, UPM) %>%
            mutate(M = 1)

# Se vuelve a cargar la base de datos para fines practicos
ZM_2010 <- read.xlsx(paste0(here::here(), "/Bases/Municipio/ZM_2010.xlsx"), sheet = "ZM_2010") %>%
            mutate(CVE_ENT = stringr::str_pad(.$CVE_ENT, width = 3, side = c("left"), pad = "0"),
                   CVE_MUN = stringr::str_pad(.$CVE_MUN, width = 6, side = c("left"), pad = "0"))

Entidades y Municipios

Se genera un vector con el nombre de las entidades llamado estados para facilitar los filtros en el documento.
Se genera un vector con las abreviaturas de las entidades llamado ent para fines prácticos.
Se genera un vector con las claves de los municipios.

# Claves de los estados
estados <- sjlabelled::get_labels(mydata$CVE_ENT)

nom_estados <- c( "Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila de Zaragoza", "Colima", 
                  "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",        
                  "México", "Michoacán de Ocampo", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
                  "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
                  "Veracruz de Ignacio de la Llave", "Yucatán", "Zacatecas")

est <- c("AGS", "BC", "BCS", "CAMP", "COAH", "COL", "CHIS", "CHIH", "CDMX", "DGO", "GTO", "GRO", "HGO",
         "JAL", "MEX", "MICH", "MOR", "NAY", "NL", "OAX", "PUE", "QRO", "QROO", "SLP","SIN","SON", "TAB", 
         "TAMS", "TLX", "VER", "YUC", "ZAC")

# Claves de los municipios
MUN <- readRDS(paste0(here::here(), "/Bases/municipios_2010.RDS"))
nom_municipios <- sjlabelled::get_labels(MUN$NOM_MUN) %>% as.factor()
municipios <- sjlabelled::get_labels(MUN$CVE_MUN) %>% as.factor()
#saveRDS(MUN, file = paste0(here::here(), "/Bases/municipios_2010.RDS"))

# Claves de las zonas metropolitanas
zm <- sjlabelled::get_labels(mydata$CVE_ZM)[-2]
nom_zm <- sjlabelled::get_labels(mydata$NOM_ZM)[-2]

Migración reciente

Migración interna

Matrices

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       select(CVE_ENT, CVE_MUN, RES05EDO_C, CVE_MUN_RES, CVE_ZM, CVE_ZM_RES, M, EDAD, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2010 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_RES5A_ZM_2010 = ifelse(is.na(.$CVE_ZM_RES), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_RES ~ 'Pertenecen a la Zona Metropolitana', #Residentes
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '1' & .$CVE_ZM == .$CVE_ZM_RES ~ "Pertenecen a la Zona Metropolitana", #Migrantes que residen en la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '1' & .$CVE_ZM != .$CVE_ZM_RES ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residen en otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian fuera de la zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '0' & .$I_RES5A_ZM_2010 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian dentro de una zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '0' & .$I_RES5A_ZM_2010 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Migrantes que no residen en la zona metropolitana
                                )) %>%
         filter(EDAD >= 5 & EDAD <= 130) %>%
          filter(CVE_MUN_RES %in% municipios) %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/MC_municipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/MC_municipal.RDS"))

Migrantes <- svytable(~CVE_MUN_RES + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_RES, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 20)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Reciente")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.xlsx"), overwrite = TRUE)

Matriz de migración reciente hace 5 años a nivel municipal, 2005 - 2010

Matriz de migración reciente 2005 - 2010
Nivel municipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 665374 597 552 0 762 121 124 17 98 17 269 104 235 182 359 0 0 0 0 70 0 0 0 0 0 0 0 0 0
001002 168 38598 0 0 0 12 0 0 0 15 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 76 0 44589 14 16 0 22 0 0 11 0 0 0 0 11 0 0 0 0 0 0 0 0 11 0 0 0 0 0
001004 50 0 0 12248 0 0 19 0 0 4 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 1875 22 0 0 77233 140 36 22 16 0 389 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 145 36 0 6 140 33542 96 38 20 18 234 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 36 45 18 54 45 75 40417 0 0 0 18 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 52 8 8 2 10 20 14 5934 0 0 2 0 0 0 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 90 10 0 25 0 53 258 10 16525 5 0 13 0 0 52 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 78 33 0 0 4 0 0 5 0 15235 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 2577 64 48 0 787 1068 204 22 80 0 24496 0 100 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 67 0 0 0 0 0 0 0 0 0 0 367600 3703 142 3105 641 97 403 1370 47 0 0 0 0 57 0 0 0 0
002002 903 0 0 0 0 0 0 0 0 0 0 1889 798622 761 2416 536 48 189 72 25 0 0 0 0 0 0 0 0 0
002003 50 0 0 0 0 0 11 0 0 0 0 222 654 74714 1642 64 0 45 27 6 0 0 0 0 0 0 0 0 0
002004 812 0 0 0 12 147 0 0 0 0 0 1905 2442 472 1248126 1414 0 0 956 100 0 0 0 0 0 0 0 0 0
002005 78 0 0 0 0 0 0 0 0 0 0 276 434 35 3920 66316 0 0 36 10 0 0 0 26 0 0 0 0 0
003001 48 0 0 0 0 0 0 0 0 0 0 163 70 0 282 34 57665 310 1220 736 66 0 0 0 0 0 0 0 0
003002 233 0 0 0 0 0 0 0 0 0 0 990 35 15 260 45 56 43931 408 50 71 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 603 449 0 854 0 2344 1108 204067 2520 391 0 0 0 0 0 0 0 0
003008 24 0 0 0 0 0 0 0 0 0 0 287 239 4 1374 56 260 13 1861 151222 180 0 0 0 0 0 0 0 0
003009 14 0 0 0 0 0 0 0 0 0 0 105 35 0 100 7 392 287 205 175 12240 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 45660 0 11 11 33 11 11 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 7 0 34 0 0 0 0 0 0 139 226429 277 285 146 94 13 6
004003 0 0 0 0 0 0 0 0 0 0 0 166 0 0 34 0 0 0 16 0 0 0 162 179398 66 0 0 226 0
004004 33 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 85 0 1024 67194 72 33 33 36
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 38 10 30 25 23321 0 10 15
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 26 14 14 42 21 32956 14 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 3 0 24 3 0 0 8250 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 15 38 14 9 37 9 10 8275
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 11 0 0 0 0 0 0 22 11 462 240 110 11 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Se filtran los flujos migratorios que son exclusivos de las zonas metropolitanas y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2010 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 0) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2010 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2010 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM = ZM, tabla = Migrantes)

Emigrantes <- Emigrantes_function(ZM = ZM, tabla = Migrantes) 

################################## Filtro ######################################
#p <- data.frame(ZM = ZM_CF,
 #               filtro_municipio = tabla_municipios,
  #              filtro_estado = tabla_estados)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Filtro a nivel municipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
tabla1 <- migration_flows_metropolitan(tabla = Migrantes, 
                                       filtro_zm = ZM, 
                                       filtro_mig = filtro_mig, 
                                       filtro_out = filtro_out, 
                                       Emigrantes = Emigrantes, 
                                       Inmigrantes = Inmigrantes, 
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group = "Otros estados")

## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:length(ZM_CF), function(i){
#                                           tabla1[[i]] %>%
#                                            as.data.frame() %>%
#                                             adorn_totals(c("row", "col"), 
#                                                           fill = "-", 
#                                                            na.rm = TRUE, 
#                                                             ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                              select(`Otros estados`) %>%
#                                               slice(nrow(.)) %>%
#                                                mutate(`Otros estados` = .$`Otros estados`/4) %>%
#                                                 pull(`Otros estados`)
#})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                              p <- tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      slice(-nrow(.))
#                              if(sum(p) == 0) {
#                                return(0)
#                              } else {
#                                p %>% 
#                                 adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm =  TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/50) %>%
#                                                    pull(Total)
#                              }
#})

## Se guardan las matrices de migración reciente para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Tabla MR5a a nivel municipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Tabla MR5a a nivel municipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Inmigrantes",  
                        Emigrantes = "Emigrantes")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Inmigrantes",  
                                  Emigrantes = "%Emigrantes")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel municipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Tabla MR5a a nivel municipal.RDS"))

## Paleta de colores 
#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/ChordDiagram de MR5a desagregado por ZM.pdf"
 
## Gráficos a nivel municipal 
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.2,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text = c(-0.05, 0.5),
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = c(0, 0, 0, 0))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Etiquetas a nivel municipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 9, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(NOM_ZM_CF[,1], NOM_ZM_CF[,2]))

Gráfico Sankey

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 25)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2010 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 3) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)


################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 0)

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   filter(value > 0)

################################################################################

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                    ZM <- ZM_2010 %>%
                                           select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                            filter(CVE_ZM %in% ZM_CF[x])  %>%
                                             mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                              pull(NOM_MUN)
                                    
                                    # filtro de municipios metropolitanos
                                     filtro <- filtro %>%
                                      filter(rn %in% ZM) %>%
                                       filter(value < 1000) %>%
                                        pull(rn)
                                     
                                    # filtro de estados
                                     filtro_rn  <- filtro_est %>%
                                                    mutate(value = ifelse(.$rn %nin% filtro |.$cn %nin% filtro, value, 0)) %>%
                                                     mutate(rn = substr(.$rn, 1, 3)) %>%
                                                      group_by(rn) %>%
                                                       summarise(Inm = sum(value, na.rm = TRUE))
              
                                     filtro_cn  <- filtro_est %>%
                                                    mutate(value =  ifelse(.$rn %nin% filtro |.$cn %nin% filtro, value, 0)) %>% 
                                                     mutate(cn = substr(.$cn, 1, 3)) %>%
                                                      group_by(cn) %>%
                                                       summarise(Emg = sum(value, na.rm = TRUE))
              
                                     filtro_estados <- filtro_rn %>%
                                                        full_join(., filtro_cn, by = c("rn" = "cn")) %>%
                                                         mutate(value = sum_row(.$Inm, .$Emg, na.rm = TRUE)) %>%
                                                          filter(value > 5000) %>%
                                                           pull(rn)
                                     
                                     tabla %>%
                                      mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), .$value, 0)) %>%
                                       mutate(rn = case_when(.$rn %in% ZM & .$rn %nin% filtro ~ .$rn,
                                                             .$rn %in% ZM & .$rn %in% filtro ~ paste(substr(.$rn, 1, 3), "Municipios ZM"),
                                                             .$rn %nin% ZM  &  substr(.$rn, 1, 3) %in% filtro_estados ~ paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]),
                                                             .$rn %nin% ZM  &  substr(.$rn, 1, 3) %nin% filtro_estados ~ "Otros estados"),
                                              cn = case_when(.$cn %in% ZM & .$cn %nin% filtro ~ .$cn,
                                                             .$cn %in% ZM & .$cn %in% filtro ~ paste(substr(.$cn, 1, 3), "Municipios ZM"),
                                                             .$cn %nin% ZM  &  substr(.$cn, 1, 3) %in% filtro_estados ~ paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]),
                                                             .$cn %nin% ZM  &  substr(.$cn, 1, 3) %nin% filtro_estados ~ "Otros estados")) %>%
                                        dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE, fill = 0) %>%
                                         column_to_rownames(., var = "rn") 
  }
)
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
               ggplot(aes(axis1 = rn, 
                           axis2 = cn, 
                            y = value),  # c("value", "freq", "tasa")
                       reverse = FALSE, 
                        na.rm = TRUE) +
                geom_alluvium(aes(fill = rn),
                               curve_type = "quintic", 
                                color = "transparent", 
                                 alpha = 0.85, 
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                  geom_stratum(aes(fill = cn), 
                                color = "white", 
                                 alpha = 0.65,  
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3, 
                                      direction = "y", 
                                       nudge_x = -.2,
                                        min.segment.length = unit(1, "lines"),
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                    geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                     stat = "stratum", 
                                      size = 3,
                                       direction = "y", 
                                        nudge_x = .2, 
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 7, family = "montserrat"),
                                   legend.position = c(1.02, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.5)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(),"/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/GSankey de MR5a desagregado por ZM_Absolutos.pdf")
ggexport(list = p, width = 18, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2010 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "13.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM = ZM, tabla = Migrantes)

Emigrantes <- Emigrantes_function(ZM = ZM, tabla = Migrantes)      

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 40000) %>% 
               pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value >= 25000) %>% 
                      pull(rn)

################################################################################
tabla1 <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                            filtro_zm = ZM, 
                                            filtro_municipios = filtro, 
                                            filtro_estados = filtro_est, 
                                            category_group = estados, 
                                            category_names = nom_estados,
                                            group = "Otros estados") %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 
# Paleta de colores
#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/ChordDiagram de MR5a de ZMVM.pdf"

## Gráficos a nivel zona metropolitana (ZMVM)
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.1,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.1, 0.5),
                    adj.ylim = 0.2,
                    gap.degree = 3, 
                    clock.wise = TRUE,
                    track.margin = c(-0.2, 0.2),
                    margin = rep(1.5, 4))
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2010 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "13.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM = ZM, tabla = Migrantes)

Emigrantes <- Emigrantes_function(ZM = ZM, tabla = Migrantes)   

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 30000) %>% 
               pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value >= 25000) %>% 
                      pull(rn)

################################################################################
tabla <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                           filtro_zm = ZM, 
                                           filtro_municipios = filtro, 
                                           filtro_estados = filtro_est, 
                                           category_group = estados, 
                                           category_names = nom_estados,
                                           group = "Otros estados")  

tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()
# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()
# Grupo 4
grupo4 <- tabla %>%
           filter(substr(.$rn, 1, 2) %nin% c("09", "15", "13")) %>%
            pull(rn) %>%
             unique()

## Se guardan las matrices de migración reciente para analizarlos después. 
tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
                         ,,,,contains(str_sort(unique(c(colnames(tabla1), rownames(tabla1))), numeric = TRUE)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a de ZMVM a nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
# Paleta de colores
#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/ChordDiagram de MR5a de ZMVM_grupos (Intermunicipal).pdf"

chord_diagram_graph_zmvm(file = file, 
                         width = 10, 
                         height = 10, 
                         family = "Montserrat Medium", 
                         paleta = paleta, 
                         tabla1 = as.matrix(tabla1), 
                         color_labels = "#000C7D",
                         transparency = 0.1,
                         circo.text = 9,
                         circos.axis.text = 7,
                         adj.text = c(-0.01, 0.5),
                         adj.ylim = 1,
                         gap.degree = 3, 
                         clock.wise = FALSE,
                         track.margin = c(-0.2, 0.2),
                         margin = rep(0, 4), 
                         group1 = grupo1, 
                         group1.text = "Ciudad de México",
                         group1.col = 1, 
                         group2 = grupo2, 
                         group2.text = "México",
                         group2.col = 15, 
                         group3 = grupo3, 
                         group3.text = "Hidalgo",
                         group3.col = 20, 
                         group4 = grupo4, 
                         group4.text = "Otro municipios",
                         group4.col = 30) 

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Etiquetas ZMVM a nivel intermunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 9, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = "ZM del Valle de México")
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2010 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "13.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(rn %in% ZM) %>%
               filter(value < 50000) %>% 
                pull(rn)

### filtro de estados
filtro_rn <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & .$rn %in% ZM |.$cn %in% ZM, value, 0)) %>%
                    filter(value > 0) %>%
                     mutate(rn = substr(.$rn, 1, 3)) %>%
                      group_by(rn) %>%
                       summarise(Inm = sum(value, na.rm = TRUE))                                     
              
filtro_cn <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value =  ifelse((.$rn != .$cn) & .$rn %in% ZM |.$cn %in% ZM, value, 0)) %>% 
                    filter(value > 0) %>%
                     mutate(cn = substr(.$cn, 1, 3)) %>%
                      group_by(cn) %>%
                       summarise(Emg = sum(value, na.rm = TRUE))  

filtro_estados <- filtro_rn %>%
                   full_join(., filtro_cn, by = c("rn" = "cn")) %>%
                    mutate(value = sum_row(.$Inm, .$Emg, na.rm = TRUE)) %>%
                     filter(value > 50000) %>%
                      pull(rn)

################################################################################
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%                       
               mutate(rn = case_when(.$rn %in% ZM & .$rn %nin% filtro ~ .$rn,
                                     .$rn %in% ZM & .$rn %in% filtro ~ paste(substr(.$rn, 1, 3), "Municipios ZM"),
                                     .$rn %nin% ZM  &  substr(.$rn, 1, 3) %in% filtro_estados ~ paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]),
                                     .$rn %nin% ZM  &  substr(.$rn, 1, 3) %nin% filtro_estados ~ "Otros estados"),
                      cn = case_when(.$cn %in% ZM & .$cn %nin% filtro ~ .$cn,
                                     .$cn %in% ZM & .$cn %in% filtro ~ paste(substr(.$cn, 1, 3), "Municipios ZM"),
                                     .$cn %nin% ZM  &  substr(.$cn, 1, 3) %in% filtro_estados ~ paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]),
                                     .$cn %nin% ZM  &  substr(.$cn, 1, 3) %nin% filtro_estados ~ "Otros estados")) %>%
                filter(value > 0) 

p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.85,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/GSankey de MR5a de la ZMVM.pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora.

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 5 años y más ###############################
Pob.5ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 5 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.5ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_RES) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_RES) %>%
                     group_by(CVE_MUN_RES) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_RES") 

tabla <- Pob.Total %>%
          left_join(., Pob.5ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Indicadores de MR5a por ZM 2010.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Indicadores de MR5a por ZM 2010.RData"))
Indicadores de migración reciente a nivel municipal
Zonas Metropolitanas
CVE_MUN Pob.Total Pob.5ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 793 997 718 680 665 374 39 438 26 908 12 530 66 346 10.4 7.1 3.3 −53 816
001002 45 951 40 347 38 598 721 1 381 −660 2 102 3.3 6.4 −3.1 −2 762
001003 53 142 47 809 44 589 884 1 454 −570 2 338 3.5 5.8 −2.3 −2 908
001004 14 302 12 759 12 248 203 266 −63 469 3.0 3.9 −0.9 −532
001005 100 150 87 268 77 233 6 005 2 733 3 272 8 738 12.8 5.8 7.0 −5 466
001006 40 480 35 933 33 542 1 681 1 868 −187 3 549 8.8 9.8 −1.0 −3 736
001007 48 462 42 246 40 417 575 1 269 −694 1 844 2.5 5.6 −3.1 −2 538
001008 7 164 6 374 5 934 182 133 49 315 5.4 3.9 1.4 −266
001009 20 048 17 674 16 525 700 263 437 963 7.4 2.8 4.6 −526
001010 18 282 16 022 15 235 313 812 −499 1 125 3.6 9.5 −5.8 −1 624
001011 36 822 31 901 24 496 6 348 1 208 5 140 7 556 36.9 7.0 29.9 −2 416
002001 460 793 419 052 367 600 37 646 20 037 17 609 57 683 17.1 9.1 8.0 −40 074
002002 932 001 852 568 798 622 34 217 29 286 4 931 63 503 7.7 6.6 1.1 −58 572
002003 95 638 86 305 74 714 7 838 4 977 2 861 12 815 17.2 10.9 6.3 −9 954
002004 1 543 644 1 391 497 1 248 126 90 073 90 788 −715 180 861 12.3 12.4 −0.1 −181 576
002005 91 309 82 225 66 316 10 427 5 647 4 780 16 074 24.0 13.0 11.0 −11 294
003001 70 358 63 992 57 665 5 234 3 685 1 549 8 919 15.6 11.0 4.6 −7 370
003002 58 624 52 519 43 931 7 587 3 771 3 816 11 358 27.3 13.6 13.7 −7 542
003003 249 303 229 448 204 067 23 278 12 977 10 301 36 255 19.4 10.8 8.6 −25 954
003008 238 498 213 476 151 222 51 192 13 125 38 067 64 317 45.3 11.6 33.7 −26 250
Fuente: Estimaciones del CONAPO.

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migración intramunicipal

Matrices

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       select(CVE_ENT, CVE_MUN, RES05EDO_C, CVE_MUN_RES, CVE_ZM, CVE_ZM_RES, M, EDAD, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2010 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_RES5A_ZM_2010 = ifelse(is.na(.$CVE_ZM_RES), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_RES ~ 'Pertenecen a la Zona Metropolitana', #Residentes
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '1' & .$CVE_ZM == .$CVE_ZM_RES ~ "Pertenecen a la Zona Metropolitana", #Migrantes que residen en la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '1' & .$CVE_ZM != .$CVE_ZM_RES ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residen en otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian fuera de la zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '0' & .$I_RES5A_ZM_2010 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian dentro de una zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '0' & .$I_RES5A_ZM_2010 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Migrantes que no residen en la zona metropolitana
                                )) %>%
         filter(EDAD >= 5 & EDAD <= 130) %>%
          filter(CVE_MUN_RES %in% municipios & .$I_ZM %in% "Pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/MC_intramunicipal.RDS"))

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/MC_intramunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_RES + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_RES, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 20)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2010.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2010.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intramunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2010.xlsx"), overwrite = TRUE)

Matriz de migración reciente hace 5 años a nivel municipal, 2005 - 2010

Matriz de migración reciente por zonas metropolitanas
Nivel intramunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 665374 0 0 0 762 0 0 0 0 0 269 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 0 38598 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 0 0 44589 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 0 0 0 12248 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 1875 0 0 0 77233 0 0 0 0 0 389 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 0 0 0 0 0 33542 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 0 0 0 0 0 0 40417 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 0 0 0 0 0 0 0 5934 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 0 0 0 0 0 0 0 0 16525 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 0 0 0 0 0 0 0 0 0 15235 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 2577 0 0 0 787 0 0 0 0 0 24496 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 367600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 0 8e+05 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 0 0 74714 1642 64 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 0 0 472 1248126 1414 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 0 0 35 3920 66316 0 0 0 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 57665 0 0 0 0 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 43931 0 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2e+05 0 0 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 151222 0 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 12240 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 45660 0 0 0 0 0 0 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 226429 0 0 0 0 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 179398 0 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 67194 0 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 23321 0 0 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32956 0 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8250 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8275
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Fuente: Estimaciones del CONAPO.

Matrices por zonas metropolitanas

MR <- NULL
for(i in 1:length(zm)){
tabla <- ZM_2010 %>%
          select(CVE_ZM, CVE_MUN) %>%
           filter(CVE_ZM %in% zm[i]) %>%
            pull(CVE_MUN)

MR[[paste0(zm[i])]] <- Migrantes %>%
                        as.data.frame() %>%
                         tibble::rownames_to_column(var = "CVE_MUN") %>%
                          mutate_if(is.numeric, as.numeric) %>%
                           select(CVE_MUN, all_of(tabla)) %>%
                            filter(CVE_MUN %in% tabla)
}

# Se guardan en un objeto de R 
saveRDS(MR, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matrices de MR5a a nivel intramunicipal por ZM2010.RDS"))

# Se genera un Excel con todas las matrices por ZM
wb <- createWorkbook()
for(i in 1:length(zm)){
addWorksheet(wb, paste0(zm[i]))
writeData(wb, i, MR[[paste0(zm[i])]] %>% as.data.frame())
saveWorkbook(wb, 
              file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matrices de MR5a a nivel intramunicipal por ZM2010.xlsx"), 
               overwrite = TRUE)
}

Matriz de migración reciente hace 5 años en la Zona Metropolitana de Cuernavaca, 2005 - 2010

Matriz de migración reciente a nivel intramunicipal
Zona Metropolitana de Cuernavaca
CVE_MUN 017007 017008 017009 017011 017018 017020 017024 017028
017007 305767 282 149 1412 616 680 28 217
017008 3260 61842 15 1578 858 0 60 306
017009 204 3 14775 56 28 3 0 7
017011 8303 899 0 152934 769 18 189 130
017018 2113 107 8 403 89253 0 0 231
017020 1291 50 0 1898 23 30523 0 20
017024 150 40 12 36 36 0 39740 73
017028 2041 264 0 584 1201 113 15 46715
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2010 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 3) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2010 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2010 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################# Filtro #######################################
### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
### Filtro <<<<  filter(value > 0 & rn != estado[x])
#p <- data.frame(ZM = ZM_CF,
#                filtro_municipio = tabla_municipios)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Filtro a nivel intramunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Filtro a nivel intramunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

################################################################################
tabla1 <- intramunicipal_flows_metropolitan(tabla = Migrantes,
                                            filtro_zm = ZM, 
                                            filtro_mig = filtro_mig, 
                                            Emigrantes = Emigrantes,
                                            Inmigrantes = Inmigrantes, 
                                            category_group = estados, 
                                            group = "Otros municipios")
tabla1 <- purrr::map(tabla1, ~ .x %>%
           dcast(rn ~ cn, value.var = "value", sum, na.rm = TRUE) %>%
            column_to_rownames(var = "rn"))

################################################################################
## Se guardan las matrices de migración reciente para analizarlos después.
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
                                ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel intramunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel intramunicipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Inmigrantes",  
                        Emigrantes = "Emigrantes")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Inmigrantes",  
                                  Emigrantes = "%Emigrantes")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel intramunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel intramunicipal.RDS"))

#Paleta de colores
#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/ChordDiagram de MR5a desagregado por ZM (Intramunicipal).pdf"

## Gráficos a nivel intramunicipal 
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text = c(-0.05, 0.5),
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Etiquetas ZM a nivel intramunicipal.pdf"

labels_chord_diagram(file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(NOM_ZM_CF[,1], NOM_ZM_CF[,2]))

Gráfico Sankey

## Tomamos las Zonas Metropolitanas con más de 3 municipios con flujos migratorios 
ZM_CF <- ZM_2010 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 2) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") 

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                   ZM <- ZM_2010 %>%
                                          select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                           filter(CVE_ZM %in% ZM_CF[x])  %>%
                                            mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                             pull(NOM_MUN)
                                    tabla %>%
                                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                                      filter(value > 0) 
  }
) 
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
               ggplot(aes(axis1 = rn, 
                           axis2 = cn, 
                            y = value),  # c("value", "freq", "tasa")
                       reverse = FALSE, 
                        na.rm = TRUE) +
                geom_alluvium(aes(fill = rn),
                               curve_type = "quintic", 
                                color = "transparent", 
                                 alpha = 0.85, 
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                  geom_stratum(aes(fill = cn), 
                                color = "white", 
                                 alpha = 0.65,  
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3, 
                                      direction = "y", 
                                       nudge_x = -.2,
                                        min.segment.length = unit(1, "lines"),
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                    geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                     stat = "stratum", 
                                      size = 3,
                                       direction = "y", 
                                        nudge_x = .2, 
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 9, family = "montserrat"),
                                   legend.position = c(1, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.35)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/GSankey de MR5a desagregado por ZM_Absolutos (Intramunicipal).pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2010 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "13.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 15000) %>% 
               pull(rn)

################################################################################
tabla1 <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                            filtro_zm = ZM, 
                                            filtro_municipios = filtro, 
                                            filtro_estados = NULL, 
                                            category_group = estados, 
                                            category_names = nom_estados,
                                            group = "ZMVM") %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%                        
            column_to_rownames(., var = "rn")   
#Paleta de colores
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/ChordDiagram de MR5a de ZMVM (Intramunicipal).pdf"

## Gráficos a nivel zona metropolitana (ZMVM)
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.1,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.1, 0.5),
                    adj.ylim = 0.2,
                    gap.degree = 3, 
                    clock.wise = TRUE,
                    track.margin = c(-0.2, 0.2),
                    margin = rep(1.5, 4))
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2010 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "13.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)       

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 15000) %>% 
               pull(rn)

################################################################################
################################################################################
tabla <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                           filtro_zm = ZM, 
                                           filtro_municipios = filtro, 
                                           filtro_estados = NULL, 
                                           category_group = estados, 
                                           category_names = nom_estados,
                                           group = "ZMVM") 

tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()
# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()

## Se guardan las matrices de migración reciente para analizarlos después. 
tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
                         ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a de ZMVM a nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
#Paleta de colores
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/ChordDiagram de MR5a de ZMVM_grupos (Intramunicipal).pdf"

## Gráficos a nivel zona metropolitana (ZMVM)
chord_diagram_graph_zmvm(file = file, 
                         width = 10, 
                         height = 10, 
                         family = "Montserrat Medium", 
                         paleta = paleta, 
                         tabla1 = as.matrix(tabla1), 
                         color_labels = "#000C7D",
                         transparency = 0.1,
                         circo.text = 9,
                         circos.axis.text = 7,
                         adj.text = c(-0.01, 0.5),
                         adj.ylim = 1,
                         gap.degree = 3, 
                         clock.wise = TRUE,
                         track.margin = c(-0.2, 0.2),
                         margin = rep(0, 4), 
                         group1 = grupo1, 
                         group1.text = "Ciudad de México",
                         group1.col = 1, 
                         group2 = grupo2, 
                         group2.text = "México",
                         group2.col = 15,
                         group3 = grupo3, 
                         group3.text = "Hidalgo",
                         group3.col = 20)

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Etiquetas ZMVM a nivel intramunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = "ZM del Valle de México")
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2010 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "13.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(value < 30000) %>% 
               pull(rn)

#########################################################################################
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = ifelse(.$rn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$rn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 20), .$rn),
                      cn = ifelse(.$cn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$cn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 20) , .$cn)) %>%
                filter(value > 0) 

p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.85,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(),"/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/GSankey de MR5a de la ZMVM (Intramunicipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora.

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 5 años y más ###############################
Pob.5ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 5 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.5ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2010.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_RES) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_RES) %>%
                     group_by(CVE_MUN_RES) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_RES") 

tabla <- Pob.Total %>%
          left_join(., Pob.5ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, 
            file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Indicadores de MR5a por ZM 2010 (Intramunicipal).xlsx"), 
             overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Indicadores de MR5a por ZM 2010 (Intramunicipal).RData"))
Indicadores de migración reciente a nivel intramunicipal
Zonas Metropolitanas
CVE_MUN Pob.Total Pob.5ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 793 997 718 680 665 374 1 031 4 452 −3 421 5 483 0.27 1.18 −0.9 −8 904
001002 45 951 40 347 38 598 0 0 0 0 0.00 0.00 0.0 0
001003 53 142 47 809 44 589 0 0 0 0 0.00 0.00 0.0 0
001004 14 302 12 759 12 248 0 0 0 0 0.00 0.00 0.0 0
001005 100 150 87 268 77 233 2 264 1 549 715 3 813 4.83 3.31 1.5 −3 098
001006 40 480 35 933 33 542 0 0 0 0 0.00 0.00 0.0 0
001007 48 462 42 246 40 417 0 0 0 0 0.00 0.00 0.0 0
001008 7 164 6 374 5 934 0 0 0 0 0.00 0.00 0.0 0
001009 20 048 17 674 16 525 0 0 0 0 0.00 0.00 0.0 0
001010 18 282 16 022 15 235 0 0 0 0 0.00 0.00 0.0 0
001011 36 822 31 901 24 496 3 364 658 2 706 4 022 19.58 3.83 15.8 −1 316
002001 460 793 419 052 367 600 0 0 0 0 0.00 0.00 0.0 0
002002 932 001 852 568 798 622 0 0 0 0 0.00 0.00 0.0 0
002003 95 638 86 305 74 714 1 706 507 1 199 2 213 3.75 1.11 2.6 −1 014
002004 1 543 644 1 391 497 1 248 126 1 886 5 562 −3 676 7 448 0.26 0.76 −0.5 −11 124
002005 91 309 82 225 66 316 3 955 1 478 2 477 5 433 9.12 3.41 5.7 −2 956
003001 70 358 63 992 57 665 0 0 0 0 0.00 0.00 0.0 0
003002 58 624 52 519 43 931 0 0 0 0 0.00 0.00 0.0 0
003003 249 303 229 448 204 067 0 0 0 0 0.00 0.00 0.0 0
003008 238 498 213 476 151 222 0 0 0 0 0.00 0.00 0.0 0
Fuente: Estimaciones del CONAPO.

Migración intermunicipal

Matrices

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       select(CVE_ENT, CVE_MUN, RES05EDO_C, CVE_MUN_RES, CVE_ZM, CVE_ZM_RES, M, EDAD, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2010 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_RES5A_ZM_2010 = ifelse(is.na(.$CVE_ZM_RES), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_RES ~ 'Pertenecen a la Zona Metropolitana', #Residentes
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '1' & .$CVE_ZM == .$CVE_ZM_RES ~ "Pertenecen a la Zona Metropolitana", #Migrantes que residen en la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '1' & .$CVE_ZM != .$CVE_ZM_RES ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residen en otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian fuera de la zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '0' & .$I_RES5A_ZM_2010 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian dentro de una zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '0' & .$I_RES5A_ZM_2010 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Migrantes que no residen en la zona metropolitana
                                )) %>%
         filter(EDAD >= 5 & EDAD <= 130) %>%
          filter(CVE_MUN_RES %in% municipios & .$I_ZM %in% "No pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/MC_intermunicipal.RDS"))

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/MC_intermunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_RES + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_RES, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 20)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2010.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2010.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intermunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2010.xlsx"), overwrite = TRUE)

Matriz de migración reciente hace 5 años a nivel intermunicipal, 2005 - 2010

Matriz de migración reciente por zonas metropolitanas
Nivel intermunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 0 597 552 0 0 121 124 17 98 17 0 104 235 182 359 0 0 0 0 70 0 0 0 0 0 0 0 0 0
001002 168 0 0 0 0 12 0 0 0 15 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 76 0 0 14 16 0 22 0 0 11 0 0 0 0 11 0 0 0 0 0 0 0 0 11 0 0 0 0 0
001004 50 0 0 0 0 0 19 0 0 4 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 0 22 0 0 0 140 36 22 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 145 36 0 6 140 0 96 38 20 18 234 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 36 45 18 54 45 75 0 0 0 0 18 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 52 8 8 2 10 20 14 0 0 0 2 0 0 0 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 90 10 0 25 0 53 258 10 0 5 0 13 0 0 52 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 78 33 0 0 4 0 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 0 64 48 0 0 1068 204 22 80 0 0 0 100 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 67 0 0 0 0 0 0 0 0 0 0 0 3703 142 3105 641 97 403 1370 47 0 0 0 0 57 0 0 0 0
002002 903 0 0 0 0 0 0 0 0 0 0 1889 0 761 2416 536 48 189 72 25 0 0 0 0 0 0 0 0 0
002003 50 0 0 0 0 0 11 0 0 0 0 222 654 0 0 0 0 45 27 6 0 0 0 0 0 0 0 0 0
002004 812 0 0 0 12 147 0 0 0 0 0 1905 2442 0 0 0 0 0 956 100 0 0 0 0 0 0 0 0 0
002005 78 0 0 0 0 0 0 0 0 0 0 276 434 0 0 0 0 0 36 10 0 0 0 26 0 0 0 0 0
003001 48 0 0 0 0 0 0 0 0 0 0 163 70 0 282 34 0 310 1220 736 66 0 0 0 0 0 0 0 0
003002 233 0 0 0 0 0 0 0 0 0 0 990 35 15 260 45 56 0 408 50 71 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 603 449 0 854 0 2344 1108 0 2520 391 0 0 0 0 0 0 0 0
003008 24 0 0 0 0 0 0 0 0 0 0 287 239 4 1374 56 260 13 1861 0 180 0 0 0 0 0 0 0 0
003009 14 0 0 0 0 0 0 0 0 0 0 105 35 0 100 7 392 287 205 175 0 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 11 11 33 11 11 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 7 0 34 0 0 0 0 0 0 139 0 277 285 146 94 13 6
004003 0 0 0 0 0 0 0 0 0 0 0 166 0 0 34 0 0 0 16 0 0 0 162 0 66 0 0 226 0
004004 33 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 85 0 1024 0 72 33 33 36
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 38 10 30 25 0 0 10 15
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 26 14 14 42 21 0 14 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 3 0 24 3 0 0 0 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 15 38 14 9 37 9 10 0
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 11 0 0 0 0 0 0 22 11 462 240 110 11 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2010 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 0) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2010 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2010 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
#p <- data.frame(ZM = ZM_CF,
 #               filtro_municipio = filtro_mig,
  #              filtro_estado = filtro_out)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Filtro a nivel intermunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
tabla1 <- migration_flows_metropolitan(tabla = Migrantes, 
                                       filtro_zm = ZM, 
                                       filtro_mig = filtro_mig, 
                                       filtro_out = filtro_out, 
                                       Emigrantes = Emigrantes, 
                                       Inmigrantes = Inmigrantes, 
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group = "Otros estados")

## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:length(ZM_CF), function(i){
#                                           tabla1[[i]] %>%
#                                            as.data.frame() %>%
#                                             adorn_totals(c("row", "col"), 
#                                                           fill = "-", 
#                                                            na.rm = TRUE, 
#                                                             ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                              select(`Otros estados`) %>%
#                                               slice(nrow(.)) %>%
#                                                mutate(`Otros estados` = .$`Otros estados`/10) %>%
#                                                 pull(`Otros estados`)
#})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                              p <- tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      slice(-nrow(.))
#                              if(sum(p) == 0) {
#                                return(0)
#                              } else {
#                                p %>% 
#                                 adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm = TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/100) %>%
#                                                    pull(Total)
#                              }
#})

## Se guardan las matrices de migración reciente para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-",   
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Tabla MR5a a nivel intermunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Tabla MR5a a nivel intermunicipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Inmigrantes",  
                        Emigrantes = "Emigrantes")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Inmigrantes",  
                                  Emigrantes = "%Emigrantes")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel intermunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Tabla MR5a a nivel intermunicipal.RDS"))

#Paleta de colores
#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/ChordDiagram de MR5a desagregado por ZM (Intermunicipal).pdf"
 
## Gráficos a nivel intermunicipal
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text = c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Etiquetas ZM a nivel intermunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(NOM_ZM_CF[,1], NOM_ZM_CF[,2]))

Gráfico Sankey

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 25)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2010 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 3) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 0)

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   filter(value > 0)

################################################################################
tabla1 <- lapply(1:length(ZM_CF), function(x){
                                    ZM <- ZM_2010 %>%
                                           select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                            filter(CVE_ZM %in% ZM_CF[x])  %>%
                                             mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                              pull(NOM_MUN)
                                    
                                    # filtro de municipios metropolitanos
                                     filtro <- filtro %>%
                                      filter(rn %in% ZM) %>%
                                       filter(value < 1000) %>%
                                        pull(rn)
                                     
                                    # filtro de estados
                                     filtro_rn  <- filtro_est %>%
                                                    mutate(value = ifelse(.$rn %nin% filtro |.$cn %nin% filtro, value, 0)) %>%
                                                     mutate(rn = substr(.$rn, 1, 3)) %>%
                                                      group_by(rn) %>%
                                                       summarise(Inm = sum(value, na.rm = TRUE))
              
                                     filtro_cn  <- filtro_est %>%
                                                    mutate(value =  ifelse(.$rn %nin% filtro |.$cn %nin% filtro, value, 0)) %>% 
                                                     mutate(cn = substr(.$cn, 1, 3)) %>%
                                                      group_by(cn) %>%
                                                       summarise(Emg = sum(value, na.rm = TRUE))
              
                                     filtro_estados <- filtro_rn %>%
                                                        full_join(., filtro_cn, by = c("rn" = "cn")) %>%
                                                         mutate(value = sum_row(.$Inm, .$Emg, na.rm = TRUE)) %>%
                                                          filter(value > 50000) %>%
                                                           pull(rn)
                                     
                                     tabla %>%
                                      mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), .$value, 0)) %>%
                                       mutate(rn = case_when(.$rn %in% ZM & .$rn %nin% filtro ~ .$rn,
                                                             .$rn %in% ZM & .$rn %in% filtro ~ paste(substr(.$rn, 1, 3), "Municipios ZM"),
                                                             .$rn %nin% ZM  &  substr(.$rn, 1, 3) %in% filtro_estados ~ paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]),
                                                             .$rn %nin% ZM  &  substr(.$rn, 1, 3) %nin% filtro_estados ~ "Otros estados"),
                                              cn = case_when(.$cn %in% ZM & .$cn %nin% filtro ~ .$cn,
                                                             .$cn %in% ZM & .$cn %in% filtro ~ paste(substr(.$cn, 1, 3), "Municipios ZM"),
                                                             .$cn %nin% ZM  &  substr(.$cn, 1, 3) %in% filtro_estados ~ paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]),
                                                             .$cn %nin% ZM  &  substr(.$cn, 1, 3) %nin% filtro_estados ~ "Otros estados")) %>%
                                        filter(value > 0)
  }
)
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
               ggplot(aes(axis1 = rn, 
                           axis2 = cn, 
                            y = value),  # c("value", "freq", "tasa")
                       reverse = FALSE, 
                        na.rm = TRUE) +
                geom_alluvium(aes(fill = rn),
                               curve_type = "quintic", 
                                color = "transparent", 
                                 alpha = 0.85, 
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                  geom_stratum(aes(fill = cn), 
                                color = "white", 
                                 alpha = 0.65,  
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3, 
                                      direction = "y", 
                                       nudge_x = -.2,
                                        min.segment.length = unit(1, "lines"),
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                    geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                     stat = "stratum", 
                                      size = 3,
                                       direction = "y", 
                                        nudge_x = .2, 
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 7, family = "montserrat"),
                                   legend.position = c(1.02, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.5)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(),"/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/GSankey de MR5a desagregado por ZM_Absolutos (Intermunicipal).pdf")
ggexport(list = p, width = 18, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2010 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "13.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             filter(rn %in% ZM) %>%
              mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
               filter(value > 8000) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 10000) %>%
                      pull(rn)

################################################################################
tabla1 <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                            filtro_zm = ZM, 
                                            filtro_municipios = filtro, 
                                            filtro_estados = filtro_est, 
                                            category_group = estados, 
                                            category_names = nom_estados,
                                            group = "Otros estados") %>%
            dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%                        
            column_to_rownames(., var = "rn")    
# Paleta de colores
#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/ChordDiagram de MR5a de ZMVM (Intermunicipal).pdf"

## Gráficos a nivel intermunicipal ZMVM 
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.1,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.1, 0.5),
                    adj.ylim = 0.2,
                    gap.degree = 3, 
                    clock.wise = FALSE,
                    track.margin = c(-0.2, 0.2),
                    margin = rep(1.5, 4))
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2010 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "13.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)  

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             filter(rn %in% ZM) %>%
              mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
               filter(value > 8000) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 10000) %>%
                      pull(rn)

################################################################################
tabla <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                           filtro_zm = ZM, 
                                           filtro_municipios = filtro, 
                                           filtro_estados = filtro_est, 
                                           category_group = estados, 
                                           category_names = nom_estados,
                                           group = "Otros estados")  

tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()
# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()
# Grupo 4
grupo4 <- tabla %>%
           filter(substr(.$rn, 1, 2) %nin% c("09", "15", "13")) %>%
            pull(rn) %>%
             unique()

## Se guardan las matrices de migración reciente para analizarlos después. 
tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
                         ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a de ZMVM a nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
# Paleta de colores
#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/ChordDiagram de MR5a de ZMVM_grupos (Intermunicipal).pdf"

## Gráficos a nivel intermunicipal ZMVM
chord_diagram_graph_zmvm(file = file, 
                         width = 10, 
                         height = 10, 
                         family = "Montserrat Medium", 
                         paleta = paleta, 
                         tabla1 = as.matrix(tabla1), 
                         color_labels = "#000C7D",
                         transparency = 0.1,
                         circo.text = 9,
                         circos.axis.text = 7,
                         adj.text = c(-0.01, 0.5),
                         adj.ylim = 1,
                         gap.degree = 3, 
                         clock.wise = FALSE,
                         track.margin = c(-0.2, 0.2),
                         margin = rep(0, 4), 
                         group1 = grupo1, 
                         group1.text = "Ciudad de México",
                         group1.col = 1, 
                         group2 = grupo2, 
                         group2.text = "México",
                         group2.col = 15, 
                         group3 = grupo3, 
                         group3.text = "Hidalgo",
                         group3.col = 20, 
                         group4 = grupo4, 
                         group4.text = "Otro municipios",
                         group4.col = 30) 

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/01_Migracion reciente/Etiquetas ZMVM a nivel intermunicipal.pdf"

## Etiquetas a nivel intermunicipal ZMVM
labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 9, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = "ZM del Valle de México")
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN, by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN, by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2010 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "13.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                      group_by(rn) %>% 
                       summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(rn %in% ZM) %>%
               filter(value > 30000) %>% 
                pull(rn)
#########################################################################################

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ .$rn,
                                     .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZMVM"), 20),
                                     .$rn %nin% ZM & .$rn %nin% filtro ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 20)),
                       
                      cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ .$cn,
                                     .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZMVM"), 20),
                                     .$cn %nin% ZM & .$cn %nin% filtro ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 20))) %>%
                filter(value > 0) 


p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.85,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/GSankey de MR5a de la ZMVM (Intermunicipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora.

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 5 años y más ###############################
Pob.5ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 5 & EDAD <= 130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.5ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2010.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_RES) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_RES) %>%
                     group_by(CVE_MUN_RES) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_RES") 

tabla <- Pob.Total %>%
          left_join(., Pob.5ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Indicadores de MR5a por ZM 2010 (Intermunicipal).xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Indicadores de MR5a por ZM 2010 (Intermunicipal).RData"))
Indicadores de migración reciente a nivel intermunicipal
Zonas Metropolitanas
CVE_MUN Pob.Total Pob.5ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 793 997 718 680 0 38 407 22 456 15 951 60 863 10.2 5.9 4.2 −44 912
001002 45 951 40 347 0 721 1 381 −660 2 102 3.3 6.4 −3.1 −2 762
001003 53 142 47 809 0 884 1 454 −570 2 338 3.5 5.8 −2.3 −2 908
001004 14 302 12 759 0 203 266 −63 469 3.0 3.9 −0.9 −532
001005 100 150 87 268 0 3 741 1 184 2 557 4 925 8.0 2.5 5.5 −2 368
001006 40 480 35 933 0 1 681 1 868 −187 3 549 8.8 9.8 −1.0 −3 736
001007 48 462 42 246 0 575 1 269 −694 1 844 2.5 5.6 −3.1 −2 538
001008 7 164 6 374 0 182 133 49 315 5.4 3.9 1.4 −266
001009 20 048 17 674 0 700 263 437 963 7.4 2.8 4.6 −526
001010 18 282 16 022 0 313 812 −499 1 125 3.6 9.5 −5.8 −1 624
001011 36 822 31 901 0 2 984 550 2 434 3 534 17.4 3.2 14.2 −1 100
002001 460 793 419 052 0 37 646 20 037 17 609 57 683 17.1 9.1 8.0 −40 074
002002 932 001 852 568 0 34 217 29 286 4 931 63 503 7.7 6.6 1.1 −58 572
002003 95 638 86 305 0 6 132 4 470 1 662 10 602 13.5 9.8 3.7 −8 940
002004 1 543 644 1 391 497 0 88 187 85 226 2 961 173 413 12.0 11.6 0.4 −170 452
002005 91 309 82 225 0 6 472 4 169 2 303 10 641 14.9 9.6 5.3 −8 338
003001 70 358 63 992 0 5 234 3 685 1 549 8 919 15.6 11.0 4.6 −7 370
003002 58 624 52 519 0 7 587 3 771 3 816 11 358 27.3 13.6 13.7 −7 542
003003 249 303 229 448 0 23 278 12 977 10 301 36 255 19.4 10.8 8.6 −25 954
003008 238 498 213 476 0 51 192 13 125 38 067 64 317 45.3 11.6 33.7 −26 250
Fuente: Estimaciones del CONAPO.

Movilidad metropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       select(CVE_ENT, CVE_MUN, RES05EDO_C, CVE_MUN_RES, CVE_ZM, CVE_ZM_RES, M, EDAD, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2010 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_RES5A_ZM_2010 = ifelse(is.na(.$CVE_ZM_RES), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_RES ~ 'Pertenecen a la Zona Metropolitana', #Residentes
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '1' & .$CVE_ZM == .$CVE_ZM_RES ~ "Pertenecen a la Zona Metropolitana", #Migrantes que residen en la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '1' & .$CVE_ZM != .$CVE_ZM_RES ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residen en otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian fuera de la zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '0' & .$I_RES5A_ZM_2010 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian dentro de una zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '0' & .$I_RES5A_ZM_2010 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Migrantes que no residen en la zona metropolitana
                                )) %>%
         filter(EDAD >= 5 & EDAD <= 130) %>%
          filter(CVE_MUN_RES %in% municipios) %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/MC_metropolitana.RDS"))

Matrices

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/MC_metropolitana.RDS"))

Migrantes <- svytable(~CVE_ZM_RES + CVE_ZM, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_ZM, CVE_ZM_RES, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_ZM" = "row_labels") %>% 
                  arrange(CVE_ZM) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_ZM = substr(.$CVE_ZM, 8, 12)) %>% 
              pull(CVE_ZM)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_ZM" = ".") %>%
                mutate(`CVE_ZM` = substr(.$CVE_ZM, 12, 16)) %>%
                 pull(CVE_ZM)

# Se elimina la variable CVE_ZM
Migrantes <- Migrantes %>%
              select(-CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de MR5a a nivel metropolitano 2010.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de MR5a a nivel metropolitano 2010.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Metropolitano")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_ZM"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de MR5a a nivel metropolitano 2010.xlsx"), overwrite = TRUE)

Matriz de migración reciente hace 5 años a nivel municipal, 2005 - 2010

Matriz de migración reciente por zonas metropolitanas
Zonas metropolitanas
CVE_ZM 01.01 02.01 03.01 04.01 05.01 06.01 07.01 08.01 09.01 10.01 11.01 12.01 13.01 14.01 15.01 16.01 17.01 18.01 19.01 20.01 21.01 22.01 23.01 24.01 25.01 26.01 27.01 28.01 29.01
01.01 773762 541 335 587 20 124 0 42 8 386 605 465 1.1e+04 1091 0 0 450 15 44 0 4055 80 27 257 171 43 77 42 258
02.01 952 1396703 3530 727 123 0 0 1032 238 1745 863 699 7.5e+03 1396 64 33 2967 790 0 0 5380 701 654 739 1073 355 59 1088 469
03.01 903 3713 798622 224 0 0 0 44 0 75 299 115 1.2e+03 208 0 0 12 0 0 0 556 101 18 264 42 3 294 34 264
04.01 144 372 369 1049160 329 120 145 24 0 95 10130 844 1.6e+03 88 0 0 34 9 0 24 131 336 0 546 0 0 0 41 0
05.01 420 166 74 1497 693553 1443 769 39 0 198 752 723 1.1e+03 286 0 0 27 229 44 0 561 246 102 162 16 0 0 16 0
06.01 70 41 0 303 1461 274141 744 0 0 14 104 71 1.7e+02 6 0 0 6 45 0 0 390 0 0 1 0 0 0 0 0
07.01 0 0 88 445 937 989 147031 26 0 0 0 6 2.2e+02 170 0 0 0 0 0 0 17 0 0 6 30 0 0 0 84
08.01 183 734 300 75 43 48 43 267928 2037 23 192 68 1.9e+03 65 0 0 72 135 0 84 4928 384 12 41 460 1 13 0 1
09.01 0 464 56 0 13 0 0 692 114599 38 16 93 2.8e+02 34 16 0 176 0 36 0 735 61 60 0 64 0 0 0 0
10.01 0 234 20 32 4 0 0 0 0 583130 148 27 2.9e+03 20 0 0 0 0 0 0 1259 57 0 222 40 0 0 213 0
11.01 149 606 17 4538 404 24 13 56 48 0 1126568 2363 1.5e+03 241 0 0 326 84 0 0 388 0 0 186 6 20 9 307 0
12.01 0 226 298 270 498 35 0 138 0 58 2124 736724 1.2e+03 137 19 0 184 12 0 0 1226 0 0 0 75 0 0 100 0
13.01 3068 6904 1462 1314 794 125 121 501 14 3340 2998 2281 1.8e+07 4193 137 493 7650 6036 2182 2213 11835 1054 164 21567 4755 227 504 10211 3916
14.01 748 267 0 80 929 0 0 233 0 73 146 0 9.0e+03 1380627 231 0 287 57 22 398 2690 252 0 805 1120 233 106 122 0
15.01 55 107 0 0 0 0 0 0 0 30 0 0 5.8e+02 2301 154528 9 0 64 0 0 68 0 16 53 30 0 27 20 0
16.01 14 14 0 0 0 0 0 14 30 0 45 0 2.7e+02 69 0 98024 0 0 0 0 44 0 0 0 446 15 0 30 28
17.01 146 900 70 36 0 0 0 61 0 0 278 0 4.0e+03 44 0 0 744583 88 1 16 347 93 0 524 93 0 0 611 58
18.01 87 408 27 0 128 8 0 231 0 10 114 72 2.4e+04 176 0 0 325 415419 1145 477 727 208 0 422 74 22 0 382 154
19.01 16 81 0 62 1 0 0 12 0 0 130 0 3.5e+03 24 0 0 56 649 201680 79 138 33 0 75 6 0 50 162 32
20.01 55 26 149 0 6 0 5 0 0 7 94 0 3.3e+03 83 0 11 19 308 108 175579 62 29 6 155 72 8 7 63 0
21.01 1229 4748 1002 240 150 57 109 1848 483 647 1038 764 1.5e+04 1947 0 150 856 589 126 891 3787943 2565 1024 1334 2136 1075 770 567 1
22.01 1187 1130 382 0 12 14 40 387 141 497 189 103 2.6e+03 154 0 132 1180 61 0 36 6959 285742 102 131 155 0 15 156 102
23.01 0 169 31 19 0 0 0 146 0 16 22 0 3.0e+02 92 0 0 0 0 0 0 1258 45 119397 18 9 28 109 0 0
24.01 201 978 24 0 378 92 0 81 0 80 87 79 5.0e+04 217 0 0 570 895 40 56 1556 77 6 1631700 1708 31 11 441 339
25.01 435 883 70 27 89 0 0 88 0 34 107 0 9.2e+03 585 0 530 131 329 80 0 2079 65 0 1043 693439 471 54 82 0
26.01 4 312 37 225 0 0 0 0 154 0 0 75 4.4e+02 122 0 0 13 13 15 5 949 5 0 7 644 206111 192 30 32
27.01 0 124 0 0 0 0 0 0 0 0 0 0 3.6e+02 30 0 0 69 9 0 0 287 0 0 0 105 56 215993 10 0
28.01 342 460 178 81 0 0 0 42 0 108 63 73 2.4e+04 41 0 0 1593 122 1 296 364 328 0 774 312 113 14 772328 2045
29.01 0 171 0 1 34 0 0 0 0 99 89 48 9.8e+03 21 0 0 503 13 53 36 145 39 15 619 32 0 9 2237 356559
30.01 206 2477 503 14 96 0 25 34 40 82 233 38 1.5e+03 73 0 0 20 0 0 0 1850 1384 0 81 455 0 0 31 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de MR5a a nivel metropolitano 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2010 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2010 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

################################################################################
tabla1 <- lapply(1, function(x){
                         Migrantes %>%
                          as.data.frame() %>%
                           tibble::rownames_to_column(var = "rn") %>% 
                            melt(., id.vars = "rn", variable.name = "cn") %>%
                             mutate_if(is.factor, as.character) %>%
                              mutate(value = ifelse((.$rn != .$cn), value, 0)) %>% 
                               filter(value > 0) %>%
                                dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                 column_to_rownames(., var = "rn") 
})
#Paleta de colores
#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/ChordDiagram de MR5a desagregado por ZM (metropolitano).pdf"

## Gráficos a nivel metropolitano
chord_diagram_graph(file = file, 
                    width = 10, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))
Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de MR5a a nivel metropolitano 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2010 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2010 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
ZM_CF <- ZM_2010 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 0) %>%
             pull(CVE_ZM)

ZM <- ZM_2010 %>% 
       select(CVE_ZM, NOM_ZM) %>% 
        distinct(CVE_ZM, NOM_ZM) %>%
         mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
          pull(CVE_ZM)

NOM_ZM_CF <- ZM_2010 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
#p <- data.frame(ZM = ZM,
 #               filtro_zm = filtro_mig)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Filtro a nivel metropolitano.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Filtro a nivel metropolitano.xlsx"), colNames = TRUE) %>%
               pull(filtro_zm)

################################################################################
tabla1 <- metropolitan_flows(tabla = Migrantes, 
                             filtro_zm = ZM, 
                             filtro_mig = filtro_mig, 
                             Emigrantes = Emigrantes, 
                             Inmigrantes = Inmigrantes, 
                             group = "Otras zonas metropolitanas")

## Se guardan las matrices de migración reciente para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
                                ,,,,contains(colnames(tabla1[[i]])))
     addWorksheet(wb, zm[i])
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel metropolitano_Reduccion.xlsx"), 
               overwrite = TRUE)
}
saveRDS(tabla1, paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel metropolitano.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel metropolitano.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_ZM", 
                        Inmigrantes = "Inmigrantes",  
                        Emigrantes = "Emigrantes")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_ZM", 
                                  Inmigrantes = "%Inmigrantes",  
                                  Emigrantes = "%Emigrantes")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel metropolitano_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz MR5a a nivel metropolitano.RDS"))

# Paleta de colores
#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/ChordDiagram de MR5a desagregado por ZM (metropolitano)_individual.pdf"

## Gráficos a nivel metropolitano
chord_diagram_graph(file = file, 
                    width = 8, 
                    height = 8, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.15, 0.5),
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE, 
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Etiquetas ZM a nivel metropolitano.pdf"

## Etiquetas a nivel zona metropolitana
labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1,
                     labels = paste(NOM_ZM_CF[,1], NOM_ZM_CF[,2]))

Indicadores

Se realizan cálculos generales de migración:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora.

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ZM) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 5 años y más ###############################
Pob.5ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 5 & EDAD <= 130) %>%
                 group_by(CVE_ZM) %>%
                  summarise(Pob.5ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

ZM <- lapply(1:length(zm), function(x){
                 ZM_2010 %>% 
                  select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                   filter(CVE_ZM %in% zm[x])  %>% 
                    pull(CVE_MUN)
})

Residentes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN == CVE_MUN_RES)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Residentes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Residentes <- do.call(rbind.data.frame, Residentes)

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN != CVE_MUN_RES)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Inmigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Inmigrantes <- do.call(rbind.data.frame, Inmigrantes)

################################################################################
############################### Emigrantes #####################################
Emigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      t() %>%
                                       as.data.frame() %>%
                                        tibble::rownames_to_column(var = "CVE_MUN") %>%
                                         melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                          mutate_at(vars(3), as.numeric) %>%
                                           filter(CVE_MUN != CVE_MUN_RES)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Emigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Emigrantes <- do.call(rbind.data.frame, Emigrantes)

tabla <- Pob.Total %>%
          left_join(., Pob.5ymas, by = c("CVE_ZM")) %>%
          left_join(., Residentes, by = c("CVE_ZM")) %>%
          left_join(., Inmigrantes, by = c("CVE_ZM")) %>%
          left_join(., Emigrantes, by = c("CVE_ZM")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Indicadores de MR5a por ZM 2010 (Metropolitano) 2010.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Indicadores de MR5a por ZM 2010 (Metropolitano) 2010.RData"))
Indicadores de migración reciente (Nivel metropolitano)
Zonas Metropolitanas
CVE_ZM Pob.Total Pob.5ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
01.01 930 969 837 849 767 103 51 791 30 849 20 942 82 640 11.7 7.0 4.7 −61 698
02.01 1 730 591 1 560 027 1 389 156 108 338 101 412 6 926 209 750 13.2 12.3 0.8 −202 824
03.01 932 001 852 568 798 622 34 217 29 286 4 931 63 503 7.7 6.6 1.1 −58 572
04.01 1 214 931 1 100 088 1 033 706 49 996 42 833 7 163 92 829 8.6 7.4 1.2 −85 666
05.01 820 838 739 193 682 071 39 917 32 900 7 017 72 817 10.2 8.4 1.8 −65 800
06.01 316 334 285 958 271 321 10 995 10 267 728 21 262 7.3 6.8 0.5 −20 534
07.01 178 886 160 898 146 044 10 471 7 865 2 606 18 336 12.3 9.3 3.1 −15 730
08.01 330 435 303 157 256 010 38 173 22 244 15 929 60 417 24.1 14.0 10.1 −44 488
09.01 141 869 126 651 114 060 8 525 7 095 1 430 15 620 12.7 10.6 2.1 −14 190
10.01 683 404 618 615 578 472 34 105 31 912 2 193 66 017 10.5 9.8 0.7 −63 824
11.01 1 328 246 1 191 676 1 126 568 37 659 64 728 −27 069 102 387 6.0 10.3 −4.3 −129 456
12.01 847 021 777 112 735 809 26 491 26 700 −209 53 191 6.5 6.6 −0.1 −53 400
13.01 20 014 450 18 378 652 16 329 337 1 725 814 1 874 832 −149 018 3 600 646 18.0 19.5 −1.6 −3 749 664
14.01 1 604 170 1 439 519 1 378 932 35 451 29 510 5 941 64 961 4.7 3.9 0.8 −59 020
15.01 183 266 163 295 151 764 7 916 4 404 3 512 12 320 9.1 5.1 4.1 −8 808
16.01 110 797 102 458 97 380 3 612 3 543 69 7 155 6.8 6.6 0.1 −7 086
17.01 859 676 781 981 742 938 25 010 42 421 −17 411 67 431 6.1 10.3 −4.2 −84 842
18.01 515 075 468 407 393 506 67 065 46 363 20 702 113 428 27.3 18.9 8.4 −92 726
19.01 242 261 218 327 199 259 13 800 11 010 2 790 24 810 12.0 9.6 2.4 −22 020
20.01 205 954 186 851 173 905 10 276 11 621 −1 345 21 897 10.5 11.8 −1.4 −23 242
Fuente: Estimaciones del CONAPO.

Migración intrametropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       select(CVE_ENT, CVE_MUN, RES05EDO_C, CVE_MUN_RES, CVE_ZM, CVE_ZM_RES, M, EDAD, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2010 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_RES5A_ZM_2010 = ifelse(is.na(.$CVE_ZM_RES), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_RES ~ 'Pertenecen a la Zona Metropolitana', #Residentes
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '1' & .$CVE_ZM == .$CVE_ZM_RES ~ "Pertenecen a la Zona Metropolitana", #Migrantes que residen en la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '1' & .$CVE_ZM != .$CVE_ZM_RES ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residen en otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian fuera de la zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '0' & .$I_RES5A_ZM_2010 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian dentro de una zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '0' & .$I_RES5A_ZM_2010 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Migrantes que no residen en la zona metropolitana
                                )) %>%
         filter(EDAD >= 5 & EDAD <= 130) %>%
          filter(CVE_MUN_RES %in% municipios & .$I_ZM %in% "Pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/MC_intrametropolitana.RDS"))

Indicadores

Se realizan cálculos generales de migración:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora.

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ZM) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 5 años y más ###############################
Pob.5ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 5 & EDAD <=130) %>%
                 group_by(CVE_ZM) %>%
                  summarise(Pob.5ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
MR <- readRDS(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matrices de MR5a a nivel intramunicipal por ZM2010.RDS"))

Residentes <- lapply(1:length(zm), function(x){
                                     MR[[x]] %>% 
                                      as.data.frame() %>%
                                       melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                        mutate_at(vars(3), as.numeric) %>%
                                         filter(CVE_MUN == CVE_MUN_RES)  %>%
                                          summarize(Residentes =  sum(value, na.rm = TRUE)) %>% 
                                           mutate(CVE_ZM = !!paste0(zm[x])) 
})

Residentes <- do.call(rbind.data.frame, Residentes)

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- lapply(1:length(zm), function(x){
                                      MR[[x]] %>% 
                                       as.data.frame() %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN != CVE_MUN_RES)  %>%
                                           summarize(Inmigrantes =  sum(value, na.rm = TRUE)) %>% 
                                            mutate(CVE_ZM = !!paste0(zm[x])) 
})

Inmigrantes <- do.call(rbind.data.frame, Inmigrantes)

################################################################################
############################### Emigrantes #####################################
Emigrantes <- lapply(1:length(zm), function(x){
                                    MR[[x]] %>% 
                                     tibble::column_to_rownames(var = "CVE_MUN") %>%
                                      t() %>%
                                       as.data.frame() %>%
                                        tibble::rownames_to_column(var = "CVE_MUN") %>%
                                         melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                          mutate_at(vars(3), as.numeric) %>%
                                           filter(CVE_MUN != CVE_MUN_RES)  %>%
                                            summarize(Emigrantes=  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Emigrantes <- do.call(rbind.data.frame, Emigrantes)

tabla <- Pob.Total %>%
          left_join(., Pob.5ymas, by = c("CVE_ZM")) %>%
          left_join(., Residentes, by = c("CVE_ZM")) %>%
          left_join(., Inmigrantes, by = c("CVE_ZM")) %>%
          left_join(., Emigrantes, by = c("CVE_ZM")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Indicadores de MR5a por ZM 2010 (Intrametropolitano) 2010.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Indicadores de MR5a por ZM 2010 (Intrametropolitano) 2010.RData"))
Indicadores de migración reciente (Nivel intrametropolitano)
Zonas Metropolitanas
CVE_ZM Pob.Total Pob.5ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
01.01 930 969 837 849 767 103 6 659 6 659 0 13 318 1.51 1.51 0.0 −13 318
02.01 1 730 591 1 560 027 1 389 156 7 547 7 547 0 15 094 0.92 0.92 0.0 −15 094
03.01 932 001 852 568 798 622 0 0 0 0 0.00 0.00 0.0 0
04.01 1 214 931 1 100 088 1 033 706 15 454 15 454 0 30 908 2.67 2.67 0.0 −30 908
05.01 820 838 739 193 682 071 11 482 11 482 0 22 964 2.94 2.94 0.0 −22 964
06.01 316 334 285 958 271 321 2 820 2 820 0 5 640 1.87 1.87 0.0 −5 640
07.01 178 886 160 898 146 044 987 987 0 1 974 1.16 1.16 0.0 −1 974
08.01 330 435 303 157 256 010 11 918 11 918 0 23 836 7.52 7.52 0.0 −23 836
09.01 141 869 126 651 114 060 539 539 0 1 078 0.80 0.80 0.0 −1 078
10.01 683 404 618 615 578 472 4 658 4 658 0 9 316 1.43 1.43 0.0 −9 316
11.01 1 328 246 1 191 676 1 126 568 0 0 0 0 0.00 0.00 0.0 0
12.01 847 021 777 112 735 809 915 915 0 1 830 0.23 0.23 0.0 −1 830
13.01 20 014 450 18 378 652 16 329 337 1 348 556 1 348 556 0 2 697 112 14.05 14.05 0.0 −2 697 112
14.01 1 604 170 1 439 519 1 378 932 1 695 1 695 0 3 390 0.22 0.22 0.0 −3 390
15.01 183 266 163 295 151 764 2 764 2 764 0 5 528 3.19 3.19 0.0 −5 528
16.01 110 797 102 458 97 380 644 644 0 1 288 1.21 1.21 0.0 −1 288
17.01 859 676 781 981 742 938 1 645 1 645 0 3 290 0.40 0.40 0.0 −3 290
18.01 515 075 468 407 393 506 21 913 21 913 0 43 826 8.91 8.91 0.0 −43 826
19.01 242 261 218 327 199 259 2 421 2 421 0 4 842 2.10 2.10 0.0 −4 842
20.01 205 954 186 851 173 905 1 674 1 674 0 3 348 1.70 1.70 0.0 −3 348
Fuente: Estimaciones del CONAPO.

Migración intermetropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       select(CVE_ENT, CVE_MUN, RES05EDO_C, CVE_MUN_RES, CVE_ZM, CVE_ZM_RES, M, EDAD, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2010 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_RES5A_ZM_2010 = ifelse(is.na(.$CVE_ZM_RES), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_RES ~ 'Pertenecen a la Zona Metropolitana', #Residentes
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '1' & .$CVE_ZM == .$CVE_ZM_RES ~ "Pertenecen a la Zona Metropolitana", #Migrantes que residen en la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '1' & .$CVE_ZM != .$CVE_ZM_RES ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residen en otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '1' & .$I_RES5A_ZM_2010 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian fuera de la zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '0' & .$I_RES5A_ZM_2010 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian dentro de una zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2010 %in% '0' & .$I_RES5A_ZM_2010 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Migrantes que no residen en la zona metropolitana
                                )) %>%
         filter(EDAD >= 5 & EDAD <= 130) %>%
          filter(CVE_MUN_RES %in% municipios & .$I_ZM %in% "No pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/MC_intermetropolitana.RDS"))

Indicadores

Se realizan cálculos generales de migración:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora.

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ZM) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 5 años y más ###############################
Pob.5ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 5 & EDAD <=130) %>%
                 group_by(CVE_ZM) %>%
                  summarise(Pob.5ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2010.RData"))

ZM <- lapply(1:length(zm), function(x){
                    ZM_2010 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% zm[x])  %>% 
                      pull(CVE_MUN)
})

Residentes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN == CVE_MUN_RES)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Residentes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Residentes <- do.call(rbind.data.frame, Residentes)

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN != CVE_MUN_RES)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Inmigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Inmigrantes <- do.call(rbind.data.frame, Inmigrantes)

################################################################################
############################### Emigrantes #####################################
Emigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      t() %>%
                                       as.data.frame() %>%
                                        tibble::rownames_to_column(var = "CVE_MUN") %>%
                                         melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                          mutate_at(vars(3), as.numeric) %>%
                                           filter(CVE_MUN != CVE_MUN_RES)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Emigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Emigrantes <- do.call(rbind.data.frame, Emigrantes)

tabla <- Pob.Total %>%
          left_join(., Pob.5ymas, by = c("CVE_ZM")) %>%
          left_join(., Residentes, by = c("CVE_ZM")) %>%
          left_join(., Inmigrantes, by = c("CVE_ZM")) %>%
          left_join(., Emigrantes, by = c("CVE_ZM")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Indicadores de MR5a por ZM 2010 (Intermetropolitano) 2010.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2010/01_Migracion reciente/Indicadores de MR5a por ZM 2010 (Intermetropolitano) 2010.RData"))
Indicadores de migración reciente (Nivel intermetropolitano)
Zonas Metropolitanas
CVE_ZM Pob.Total Pob.5ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
01.01 930 969 837 849 0 45 132 24 190 20 942 69 322 10.2 5.5 4.7 −48 380
02.01 1 730 591 1 560 027 0 100 791 93 865 6 926 194 656 12.3 11.4 0.8 −187 730
03.01 932 001 852 568 0 34 217 29 286 4 931 63 503 7.7 6.6 1.1 −58 572
04.01 1 214 931 1 100 088 0 34 542 27 379 7 163 61 921 6.0 4.7 1.2 −54 758
05.01 820 838 739 193 0 28 435 21 418 7 017 49 853 7.3 5.5 1.8 −42 836
06.01 316 334 285 958 0 8 175 7 447 728 15 622 5.4 4.9 0.5 −14 894
07.01 178 886 160 898 0 9 484 6 878 2 606 16 362 11.2 8.1 3.1 −13 756
08.01 330 435 303 157 0 26 255 10 326 15 929 36 581 16.6 6.5 10.1 −20 652
09.01 141 869 126 651 0 7 986 6 556 1 430 14 542 11.9 9.8 2.1 −13 112
10.01 683 404 618 615 0 29 447 27 254 2 193 56 701 9.0 8.4 0.7 −54 508
11.01 1 328 246 1 191 676 0 37 659 64 728 −27 069 102 387 6.0 10.3 −4.3 −129 456
12.01 847 021 777 112 0 25 576 25 785 −209 51 361 6.3 6.4 −0.1 −51 570
13.01 20 014 450 18 378 652 0 377 258 526 276 −149 018 903 534 3.9 5.5 −1.6 −1 052 552
14.01 1 604 170 1 439 519 0 33 756 27 815 5 941 61 571 4.4 3.7 0.8 −55 630
15.01 183 266 163 295 0 5 152 1 640 3 512 6 792 5.9 1.9 4.1 −3 280
16.01 110 797 102 458 0 2 968 2 899 69 5 867 5.6 5.4 0.1 −5 798
17.01 859 676 781 981 0 23 365 40 776 −17 411 64 141 5.7 9.9 −4.2 −81 552
18.01 515 075 468 407 0 45 152 24 450 20 702 69 602 18.4 9.9 8.4 −48 900
19.01 242 261 218 327 0 11 379 8 589 2 790 19 968 9.9 7.5 2.4 −17 178
20.01 205 954 186 851 0 8 602 9 947 −1 345 18 549 8.8 10.1 −1.4 −19 894
Fuente: Estimaciones del CONAPO.

Referencias

Librerias que se usaron en el documento

package loadedversion source
Cairo 1.6-1 CRAN (R 4.3.1)
chorddiag 0.1.3 Github ()
circlize 0.4.15 CRAN (R 4.3.1)
doMC 1.3.5 R-Forge (R 4.3.1)
dplyr 1.1.3 CRAN (R 4.3.2)
expss 0.11.6 CRAN (R 4.3.1)
foreach 1.5.2 CRAN (R 4.3.1)
ggalluvial 0.12.5 CRAN (R 4.3.1)
ggplot2 3.4.3 CRAN (R 4.3.1)
ggpubr 0.6.0 CRAN (R 4.3.1)
ggrepel 0.9.3 CRAN (R 4.3.1)
ggsankey 0.0.99999 Github ()
gt 0.10.0 CRAN (R 4.3.1)
haven 2.5.3 CRAN (R 4.3.1)
Hmisc 5.1-0 CRAN (R 4.3.1)
iterators 1.0.14 CRAN (R 4.3.1)
janitor 2.2.0 CRAN (R 4.3.1)
kableExtra 1.3.4 CRAN (R 4.3.1)
knitr 1.45 CRAN (R 4.3.2)
maditr 0.8.3 CRAN (R 4.3.1)
Matrix 1.6-1.1 CRAN (R 4.3.1)
network 1.18.1 CRAN (R 4.3.1)
openxlsx 4.2.5.2 CRAN (R 4.3.1)
reshape2 1.4.4 CRAN (R 4.3.1)
sjlabelled 1.2.0 CRAN (R 4.3.1)
sna 2.7-1 CRAN (R 4.3.1)
srvyr 1.2.0 CRAN (R 4.3.1)
statnet.common 4.9.0 CRAN (R 4.3.1)
stringr 1.5.0 CRAN (R 4.3.1)
survey 4.2 Github ()
survival 3.5-5 CRAN (R 4.3.1)
tibble 3.2.1 CRAN (R 4.3.1)
tidyr 1.3.0 CRAN (R 4.3.1)

Creative Commons Licence
This work by Diana Villasana Ocampo is licensed under a Creative Commons Attribution 4.0 International License.